<template>
  <div class="crud-generator">
    <el-form :model="config" label-width="120px">
      <!-- 表名输入 -->
      <el-form-item label="表名" required>
        <el-input
          v-model="config.tableName"
          placeholder="请输入表名包含前缀，如:bs_order"
          style="width: 250px"
        />
        <el-button style="margin-left: 20px" size="medium" type="primary"
                   @click="handleTableNameChange(config.tableName)"
                   :loading="isLoading"
        >查询
        </el-button>
      </el-form-item>
      <el-form-item label="后台接口配置" v-if="columns.length">
        <el-checkbox-group v-model="admin_apis">
          <el-checkbox label="list">数据列表</el-checkbox>
          <el-checkbox label="get">查看详情</el-checkbox>
          <el-checkbox label="list_options">下拉选项</el-checkbox>
          <el-checkbox label="status">快速修改状态</el-checkbox>
          <el-checkbox label="save_data">增改</el-checkbox>
          <el-checkbox label="del_data">删除</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="前端接口配置" v-if="columns.length">
        <el-checkbox-group v-model="apis">
          <el-checkbox label="list">数据列表</el-checkbox>
          <el-checkbox label="detail">数据详情</el-checkbox>
          <el-checkbox label="action">增改操作</el-checkbox>
          <el-checkbox label="setDefault">设为默认</el-checkbox>
          <el-checkbox label="remove">删除</el-checkbox>
          <el-checkbox label="list_options">下拉选项</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="是否创建权限" v-if="columns.length">
        <el-switch v-model="isCreatePermission">
        </el-switch>

      </el-form-item>
      <el-form-item label="菜单名称" v-if="columns.length && isCreatePermission">
        <el-input v-model="menu_name" placeholder="请输入菜单名称" style="width: 250px"/>
        <br>
        <span>
          相关权限将设置在该菜单下，后期可以自行修改位置。多次操作同一个表以第一次为准！
        </span>
      </el-form-item>
      <el-form-item label="生成前端文件" v-if="columns.length">
        <div style="color: red">
          前端文件会生成在/runtime/temp/下的admin目录和app目录，分别对应管理后台和uniapp文件，自己复制到相应目录调整代码即可。
        </div>
      </el-form-item>
      <!-- 字段配置区域 -->
      <template v-if="columns.length">
        <div class="columns-config">
          <h3>字段配置</h3>
          <el-table :data="columns" border>
            <el-table-column prop="Field" label="字段名" width="180"/>
            <el-table-column prop="Comment" label="字段注释" width="200"/>

            <!-- 搜索配置 -->
            <el-table-column label="搜索配置" width="250">
              <template #default="{ row }">
                <el-checkbox v-model="row.isSearchable">
                  可搜索
                </el-checkbox>
                <el-input
                  v-if="row.isSearchable"
                  v-model="row.searchDisplayName"
                  size="small"
                  placeholder="显示名称"
                />
                <el-input-number
                  v-if="row.isSearchable"
                  v-model="row.searchOrder"
                  :min="1"
                  size="small"
                  placeholder="排序"
                />
              </template>
            </el-table-column>
            <el-table-column label="列表字段" width="200">
              <template #default="{ row }">
                <el-checkbox v-model="row.isShowList">
                  显示在列表
                </el-checkbox>
                <el-input
                  v-if="row.isShowList"
                  v-model="row.ShowListDisplayName"
                  size="small"
                  placeholder="显示名称"
                />
                <el-input-number
                  v-if="row.isShowList"
                  v-model="row.showListOrder"
                  :min="1"
                  size="small"
                  placeholder="排序"
                />
              </template>
            </el-table-column>

            <!-- 表单配置 -->
            <el-table-column label="表单配置" width="200">
              <template #default="{ row }">
                <el-checkbox v-model="row.isEditable">可编辑</el-checkbox>
                <el-checkbox v-model="row.isRequired">必填</el-checkbox>
              </template>
            </el-table-column>

            <!-- 字段类型 -->
            <el-table-column label="字段类型" width="200">
              <template #default="{ row }">
                <el-select v-model="row.componentType">
                  <el-option label="输入框" value="input"/>
                  <el-option label="日期选择器" value="datePicker"/>
                  <el-option label="选择器" value="select"/>
                  <el-option label="数字输入框" value="inputNumber"/>
                  <el-option label="开关" value="switch"/>
                </el-select>
              </template>
            </el-table-column>

            <!-- 选项配置 -->
            <el-table-column label="选项配置" width="200">
              <template #default="{ row }">
                <el-button
                  v-if="row.componentType === 'select'"
                  size="small"
                  @click="handleConfigOptions(row)"
                >
                  配置选项
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 生成按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleGenerate" :loading="isGenerating">生成CRUD代码</el-button>
        </el-form-item>
      </template>
    </el-form>

    <!-- 选项配置对话框 -->
    <el-dialog
      :visible.sync="optionsDialog.visible"
      v-model="optionsDialog.visible"
      title="配置选项"
      width="500px"
      modal
      lock-scroll
      :close-on-click-modal="false"
    >
      <el-form v-if="optionsDialog.currentColumn">
        <el-form-item label="选项来源">
          <el-radio-group v-model="optionsDialog.currentColumn.optionsSource">
            <el-radio label="static">静态选项</el-radio>
            <el-radio label="api">接口获取</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 静态选项配置 -->
        <template v-if="optionsDialog.currentColumn.optionsSource === 'static'">
          <div
            v-for="(option, index) in optionsDialog.currentColumn.options"
            :key="index"
            class="option-item"
          >
            <el-input v-model="option.label" placeholder="选项文本"/>
            <el-input v-model="option.value" placeholder="选项值"/>
            <el-button @click="removeOption(index)" type="danger" icon="el-icon-delete"/>
          </div>
          <el-button @click="addOption" type="primary">添加选项</el-button>
        </template>

        <!-- API选项配置 -->
        <template v-else>
          <el-form-item label="接口地址">
            <el-input v-model="optionsDialog.currentColumn.apiUrl"/>
          </el-form-item>
          <el-form-item label="标签字段">
            <el-input v-model="optionsDialog.currentColumn.labelField"/>
          </el-form-item>
          <el-form-item label="值字段">
            <el-input v-model="optionsDialog.currentColumn.valueField"/>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="optionsDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveOptions">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/curd'

export default {
  name: 'CrudGenerator',
  data() {
    return {
      config: {
        tableName: ''
      },
      isCreatePermission: true,
      menu_name: '',
      apis: ['list', 'detail'],
      admin_apis: ['list', 'get', 'list_options'],
      columns: [],
      optionsDialog: {
        visible: false,
        currentColumn: null
      },
      isLoading: false,
      isGenerating: false
    }
  },
  methods: {
    // 表名变更时查询表结构
    async handleTableNameChange(val) {
      if (!val) {
        this.columns = []
        return
      }
      // 验证表名格式
      if (!/^[a-zA-Z0-9_]+$/.test(val)) {
        this.$message.error('表名只能包含字母、数字和下划线')
        return
      }
      this.isLoading = true
      try {
        const res = await api.query_olumns({ table_name: val })
        if (res.code !== 0) {
          this.$message.error(res.msg)
          return
        }
        // 为每个字段添加配置属性
        this.columns = res.data.map(col => ({
          ...col,
          isSearchable: false,
          isShowList: true,
          showListOrder: 1,
          searchOrder: 1,
          ShowListDisplayName: col.Comment || col.Field,
          searchDisplayName: col.Comment || '', // 默认值为字段名
          isEditable: false,
          isRequired: false,
          componentType: 'input',
          optionsSource: 'static',
          options: [{ label: '默认选项', value: 'default' }], // 默认选项
          apiUrl: '',
          labelField: '',
          valueField: ''
        }))
      } catch (error) {
        console.error('获取表结构失败:', error)
        this.$message.error('获取表结构失败，请检查网络或联系管理员')
      } finally {
        this.isLoading = false
      }
    },

    // 打开选项配置对话框
    handleConfigOptions(row) {
      console.log('配置选项', row)
      if (!row.options) {
        row.options = [{ label: '默认选项', value: 'default' }]
      }
      if (!row.optionsSource) {
        row.optionsSource = 'static'
      }

      this.optionsDialog.currentColumn = JSON.parse(JSON.stringify(row))
      this.optionsDialog.visible = true
    },

    // 添加选项
    addOption() {
      if (this.optionsDialog.currentColumn) {
        this.optionsDialog.currentColumn.options.push({
          label: '新选项',
          value: ''
        })
      }
    },

    // 删除选项
    removeOption(index) {
      if (this.optionsDialog.currentColumn) {
        this.optionsDialog.currentColumn.options.splice(index, 1)
      }
    },

    // 修改保存选项方法
    saveOptions() {
      if (this.optionsDialog.currentColumn.optionsSource === 'api') {
        if (!this.optionsDialog.currentColumn.apiUrl || !this.optionsDialog.currentColumn.labelField || !this.optionsDialog.currentColumn.valueField) {
          this.$message.error('请填写完整的接口配置信息')
          return
        }
      }
      // 找到原始行数据
      const originalRow = this.columns.find(
        col => col.Field === this.optionsDialog.currentColumn.Field
      )

      if (originalRow) {
        // 更新原始行的选项相关数据
        originalRow.optionsSource = this.optionsDialog.currentColumn.optionsSource
        originalRow.options = [...this.optionsDialog.currentColumn.options]
        originalRow.apiUrl = this.optionsDialog.currentColumn.apiUrl
        originalRow.labelField = this.optionsDialog.currentColumn.labelField
        originalRow.valueField = this.optionsDialog.currentColumn.valueField
      }

      this.optionsDialog.visible = false
      this.optionsDialog.currentColumn = null
    },

    // 生成CRUD代码
    async handleGenerate() {
      if (!this.config.tableName) {
        this.$message.error('请输入表名')
        return
      }
      if (this.columns.length === 0) {
        this.$message.error('请先查询表结构')
        return
      }
      this.isGenerating = true
      try {
        const config = {
          tableName: this.config.tableName,
          admin_apis: this.admin_apis,
          apis: this.apis,
          menu_name: this.menu_name,
          isCreatePermission: this.isCreatePermission,
          columns: this.columns
        }
        console.log(config)
        // 调用后端生成代码的接口
        await api.create(config)
          .then(res => {
            if (res.code === 0) {
              this.$message.success('生成代码成功')
            } else {
              this.$message.error(res.msg)
            }
          })
        // 这里可以添加下载生成的代码或其他后续处理
      } catch (error) {
        console.error('生成代码失败:', error)
        //this.$message.error('生成代码失败，请检查网络或联系管理员')
      } finally {
        this.isGenerating = false
      }
    }
  }
}
</script>

<style scoped>
.crud-generator {
  padding: 20px;
}

.columns-config {
  margin: 20px 0;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
</style>
